import { login, getInfo } from '../../api/user'
import { getToken, setToken, removeToken } from '../../utils/auth'
import { resetRouter } from '../../router'
import i18n from "../../i18n";
import {Message} from "element-ui";


const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    id: '',
    userName: "",
  }
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token);
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERNAME:(state, userName) => {
    state.userName = userName;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { name, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ name: name.trim(), password: password.trim() }).then(user => {
        if (user == null || user.code != 0) {
          Message.error({message:  i18n.t("user.login.error"), showClose: true});
          reject(i18n.t("user.login.error"))
          return;
        }
        commit('SET_TOKEN', user.data.id);
        commit('SET_ID', user.data.id);
        commit('SET_USERNAME', user.data.userName);
        resolve()
      }).catch(error => {
        console.info(error);
        reject(error)
      })
    })
  },
  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(user => {
        console.info('login action' + JSON.stringify(user));
        if (user == null || user.code !== 0) {
          reject(this.$i18n.t("user.login.error1"))
        }

        const data = user.data;
        let roles = [];
        roles.push(data.role);
        commit('SET_NAME', data.name);
        commit('SET_ID', data.id);
        commit('SET_ROLES', roles);
        commit('SET_USERNAME', data.userName);
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

